﻿using System;

namespace EmbeddedSharp.Core.Function.String {

    /// <summary>
    /// Get a portion of the given string.
    /// 
    /// Syntax: Substring(expr, fromIdx, length);
    /// 
    /// Example:
    /// substr = Substring("Hello, world!", 0, 5); # Hello
    /// </summary>
    public class SubstringNode : FuncNode {

        public SubstringNode()
            : base() {
            base.Value = "substr";
        }

        public override object Evaluate() {
            int length = Parameters.Count;
            if (length < 3) {
                throw new ArgumentException(
                    "Usage: substr(expr, fromIdx, length);");
            }

            string expr = Convert.ToString(Parameters[length - 1].Evaluate());
            int from = Convert.ToInt32(Parameters[length - 2].Evaluate());
            int count = Convert.ToInt32(Parameters[length - 3].Evaluate());

            return expr.Substring(from, count);
        }
    }
}
